﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using db = DataContext;

namespace WebApplication
{
	public partial class Products : System.Web.UI.Page
	{
		public int thetype;
		public string guid;
		public List<int> dts = new List<int>();

		protected void Page_Load(object sender, EventArgs e)
		{
			thetype = int.Parse(Common.Query("type", "0"));
			guid = Common.Query("guid", "");
			
			using (db.DbDataContext context = new db.DbDataContext())
			{
				if (guid == "")
				{
					IQueryable<db.Product> products = context.Product;

					if (!thetype.Equals(0))
					{
						dts.Add(thetype);
						context.ProductType.Single(x => x.Id == thetype).SubTypes.ToList().ForEach(x => {
							dts.Add(x.Id);
							x.SubTypes.ToList().ForEach(y => dts.Add(y.Id));
						});
						products = products.Where(x => dts.Contains(x.Type.Value));
					}

					products_list.DataSource = products.Skip(Common.Start).Take(pager.Limit);
					products_list.DataBind();
					pager.Total = products.Count();
				} else
				{
					db.Product product = context.Product.Single(x => x.GUID == guid);
					product_name.Text = product.Name;
					product_intro.Text = product.Description;
					thetype = product.Type.Value;

					product_images.DataSource = product.Pictures.Take(4);
					product_images.DataBind();

					other_list.DataSource = product.ProductType.Product.Where(x => x.Id != product.Id).OrderByDescending(x => x.AddTime).Take(5);
					other_list.DataBind();
				}

				types.DataSource = context.ProductType.Where(x=>!x.ParentId.HasValue).OrderBy(x => x.Sort);
				types.DataBind();
			}
		}

		protected void types_ItemDataBound(object sender, RepeaterItemEventArgs e)
		{
			using (db.DbDataContext context = new db.DbDataContext())
			{
				Repeater types = e.Item.FindControl("typeslv2") as Repeater;
				types.DataSource = context.ProductType.Where(x =>
					x.ParentId == (e.Item.DataItem as db.ProductType).Id).OrderBy(x => x.Sort);
				types.DataBind();
			}
		}

		protected void typeslv2_ItemDataBound(object sender, RepeaterItemEventArgs e)
		{
			using (db.DbDataContext context = new db.DbDataContext())
			{
				Repeater types = e.Item.FindControl("typeslv3") as Repeater;
				types.DataSource = context.ProductType.Where(x =>
					x.ParentId == (e.Item.DataItem as db.ProductType).Id).OrderBy(x => x.Sort);
				types.DataBind();
			}
		}
	}
}